<template>
    <div>
        <div class="select">
            <yd-cell-item
                arrow
                type="label"
            >
                <span slot="left">提现至：</span>
                <select
                    slot="right"
                    dir="rtl"
                    v-model="select"
                >
                    <option value="alipay">支付宝</option>
                    <option value="weixin">微信</option>
                    <option value="bankcard">银行卡</option>
                </select>
            </yd-cell-item>
        </div>
        <div
            class="ali"
            v-if="select == 'alipay'"
        >
            <div>
                <span>支付宝</span>
            </div>
            <div class="aliInput">
                <span>姓名</span>
                <input
                    v-model="name"
                    type="text"
                    placeholder="请输入您的真实姓名"
                >
            </div>
            <div class="aliInput">
                <span>账号</span>
                <input
                    v-model="ali"
                    type="text"
                    placeholder="请输入您的真实支付宝账户"
                >
            </div>
        </div>

        <div
            class="wx"
            v-if="select == 'weixin'"
        >
            <div>
                <span>微信</span>
            </div>
            <div>
                <label for="upload_file">
                    <img :src="!imgurl? require('../../asset/icon/icon_up.png') :imgurl">
                    <input
                        @change="fileChange($event,'wximg')"
                        type="file"
                        id="upload_file"
                        style="display:none"
                        multiple
                    />
                </label>
                <p>上传微信收款二维码</p>
            </div>
        </div>
        <div
            class="ali"
            v-if="select == 'bankcard'"
        >
            <div>
                <span>银行卡</span>
            </div>
            <div class="aliInput">
                <span>姓名</span>
                <input
                    v-model="bankName"
                    type="text"
                    placeholder="请输入收款户名"
                >
            </div>
            <div class="aliInput">
                <span>卡号</span>
                <input
                    v-model="bankAccount"
                    type="text"
                    placeholder="请输入收款银行卡号"
                >
            </div>
            <div class="aliInput">
                <span>开户行</span>
                <input
                    v-model="bankBank"
                    type="text"
                    placeholder="请输入收款银行"
                >
            </div>
        </div>
        <header>
            <span>提现金额</span>
            <input
                type="name"
                v-model="amount"
                maxlength="7"
                placeholder="请输入提现金额"
            >
            <span>元</span>
        </header>
        <div class="headerBottom">
            可提现金额：￥{{$route.query.commision== null?0:$route.query.commision}}
        </div>
        <div class="tips">
            <span>额外扣除：¥ {{money()}} 手续费（费率{{configDeduction * 100}}%）</span>
            <span>最低提现额度：{{configMinimum}}元</span>
        </div>
        <yd-cell-group>
            <yd-cell-item
                class="contBottom"
                style="border-bottom: solid 1px #c8c3ff;"
            >
                <span slot="left">手机号：</span>
                <yd-input
                    slot="right"
                    v-model="phone"
                    ref="phone"
                    required
                    regex="mobile"
                    placeholder="请输入手机号码"
                ></yd-input>
            </yd-cell-item>
            <yd-cell-item class="contBottom">
                <input
                    v-model="SMScode"
                    type="text"
                    slot="right"
                    maxlength="4"
                    placeholder="请输入验证码"
                >
                <!-- ↓↓关键代码是这里↓↓ -->
                <yd-sendcode
                    style="border-left: solid 1px #c8c3ff;"
                    bgcolor="rgba(0,0,0,0)"
                    color="#515bff"
                    slot="right"
                    v-model="start"
                    @click.native="sendCode"
                    type="warning"
                ></yd-sendcode>
                <!-- ↑↑关键代码是这里↑↑ -->

            </yd-cell-item>
        </yd-cell-group>
        <div class="title">
            <span>上传身份证信息</span>
            <span v-if="$route.query.is_real_name == 'no'">（身份证信息只能上传一次，请谨慎上传）</span>
            <span v-if="$route.query.is_real_name !== 'no'"> 已完善</span>
        </div>
        <div
            class="cont"
            v-if="$route.query.is_real_name == 'no'"
        >
            <div>
                <label for="upload_positive">
                    <img :src="!imagesPositive? require('../../asset/icon/icon_user_positive.png') : imagesPositive">
                    <input
                        @change="fileChange($event,'positive')"
                        type="file"
                        id="upload_positive"
                        style="display:none"
                        multiple
                    />
                </label>
                <p>请提交身份证正面照片</p>
            </div>
            <div>
                <label for="upload_negative">
                    <img :src="!imagesNegative? require('../../asset/icon/icon_user_negative.png') : imagesNegative">
                    <input
                        @change="fileChange($event,'negative')"
                        type="file"
                        id="upload_negative"
                        style="display:none"
                        multiple
                    />
                </label>
                <p>请提交身份证反面照片</p>
            </div>
        </div>
        <div
            class="button"
            @click="pushData"
        >
            确认提现
        </div>
    </div>
</template>
<script>
export default {
    name: "drawMoney",
    data() {
        return {
            imagesPositive: '',
            imagesNegative: '',
            selectType: '',
            QINIUtoken: '',

            name: '',
            ali: '',
            imgurl: '',
            bankName: '',
            bankAccount: '',
            bankBank: '',

            select: 'alipay',
            radio1: '1',
            amount: '',
            start: false,
            phone: '',
            SMScode: '',
            configDeduction: 0,
            configMinimum: 0,
        };
    },
    methods: {
        sendCode() {
            if (!this.phone) {
                this.$dialog.toast({ mes: '请输入手机号', timeout: 2000 });
                return;
            }
            this.$dialog.loading.open('发送中...');
            let params = {
                mobile: this.phone,
            }
            this.$post("/index/get_sms_code", params)
                .then(res => {
                    if (res.code === 20000) {
                        setTimeout(() => {
                            this.start = true;
                            this.$dialog.loading.close();
                            this.$dialog.toast({
                                mes: '已发送',
                                icon: 'success',
                                timeout: 1500
                            });
                        }, 1000);
                    } else {
                        this.$dialog.toast({ mes: res.msg, timeout: 1000 });
                    }
                })
                .catch(err => { });




        },
        pushData() {

            if (!this.amount) {
                this.$dialog.toast({ mes: '请填写提现金额', timeout: 2000 });
                return;
            }
            if (!this.SMScode || !this.phone) {
                this.$dialog.toast({ mes: '请填写验证码或手机号', timeout: 2000 });
                return;
            }
            if (Number(this.amount) < Number(this.configMinimum)) {
                this.$dialog.toast({ mes: '您的输入的提现金额小于最低提现额度，请重新填写', timeout: 2000 });
                return;
            }
            let params = {
                type: this.select,
                money: this.amount,
                mobile: this.phone,
                sms_code: this.SMScode,
            }
            if (this.$route.query.is_real_name == 'no') {
                if (!this.imagesPositive) {
                    this.$dialog.toast({ mes: '请上传身份证正面', timeout: 2000 });
                    return;
                }
                if (!this.imagesNegative) {
                    this.$dialog.toast({ mes: '请上传身份证反面', timeout: 2000 });
                    return;
                }
                params.idcard_front_img = this.imagesPositive
                params.idcard_back_img = this.imagesNegative

            }
            switch (this.select) {
                case 'alipay':
                    if (!this.name) {
                        this.$dialog.toast({ mes: '请输入支付宝姓名', timeout: 2000 });
                        return;
                    }
                    if (!this.ali) {
                        this.$dialog.toast({ mes: '请输入支付宝账号', timeout: 2000 });
                        return;
                    }
                    params.alipay_name = this.name
                    params.alipay_num = this.ali
                    break;
                case 'weixin':
                    if (!this.imgurl) {
                        this.$dialog.toast({ mes: '请上传微信收款码', timeout: 2000 });
                        return;
                    }
                    params.weixin_img = this.imgurl
                    break;
                case 'bankcard':
                    if (!this.bankName || !this.bankAccount || !this.bankBank) {
                        this.$dialog.toast({ mes: '请完善银行提现信息', timeout: 2000 });
                        return;
                    }
                    params.bank_card_name = this.bankName
                    params.bank_card_num = this.bankAccount
                    params.bank_name = this.bankBank
                    break;

            }

            this.$post("/member/set_tixian", params)
                .then(res => {
                    if (res.code === 20000) {
                        this.$dialog.toast({
                            mes: '申请成功',
                            timeout: 1500,
                            icon: 'success',
                            callback: () => {
                                this.$router.back(-1)
                            }
                        });
                    } else if (res.code == 43015 || res.code == 43016 || res.code == 43017 || res.code == 43018 || res.code == 43019 || res.code == 43020 || res.code == 43021 || res.code == 43022) {
                        this.$dialog.confirm({
                            title: '温馨提示',
                            mes: '您所选的资料尚未完善，请完善后重新提现。',
                            opts: () => {
                                this.$router.push('/addAccount')
                            }
                        });
                    } else {
                        this.$dialog.toast({ mes: res.msg, timeout: 1000 });
                    }
                })
                .catch(err => { });
        },
        money() {
            if (!this.amount) {
                return 0;

            }
            return (this.amount * this.configDeduction).toFixed(2)
        },
        fileChange(el, type) {
            this.selectType = type
            if (!el.target.files[0].size) return;//判断是否有文件数量
            for (let i = 0; i < el.target.files.length; i++) {
                this.fileAdd(el.target.files[i]);
            }
        },
        fileAdd(file) {
            let _this = this
            this.size = this.size + file.size;//总大小
            let reader = new FileReader();
            reader.vue = this;
            reader.readAsDataURL(file);
            reader.onload = function () {
                file.src = this.result;
                _this.pushBase(file.src)

            }
        },

        pushBase(code) {

            if (!this.QINIUtoken) {
                this.$dialog.toast('七牛云token错误，请联系客服！')
                return code
            }
            let _this = this
            _this.$indicator.open({
                text: '正在上传图片...',
                spinnerType: 'fading-circle'
            });
            let pic = code
            let timestamp = new Date().getTime()
            let key = window.btoa(timestamp + '.png')
            pic = pic.replace(/^data:image\/(jpeg|png|gif);base64,/, '')
            let url = 'http://upload.qiniup.com/putb64/-1/key/' + key // 非华东空间需要根据注意事项 1 修改上传域名
            let xhr = new XMLHttpRequest()
            xhr.open('POST', url, true)
            xhr.setRequestHeader('Content-Type', 'application/octet-stream')
            xhr.setRequestHeader('Authorization', 'UpToken ' + this.QINIUtoken)
            xhr.send(pic)
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    let data = JSON.parse(xhr.responseText)
                    console.error(data);
                    console.error(_this.selectType);
                    if (_this.selectType == 'positive') {
                        _this.imagesPositive = _this.global.QINIU_URL + data.key
                    }
                    if (_this.selectType == 'negative') {
                        _this.imagesNegative = _this.global.QINIU_URL + data.key
                    }
                    if (_this.selectType == 'wximg') {
                        _this.imgurl = _this.global.QINIU_URL + data.key
                    }
                    _this.$indicator.close();
                    _this.$toast({
                        message: '上传成功',
                        position: 'middle',
                        duration: 1000,
                    });
                } else {
                    _this.imgUrl = code;
                }
            }
        },
        bytesToSize(bytes) {
            if (bytes === 0) return '0 B';
            let k = 1000, // or 1024
                sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                i = Math.floor(Math.log(bytes) / Math.log(k));
            return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
        },
        getConfig() {
            let params = {};
            this.$post("/index/get_config", params)
                .then(res => {
                    if (res.code === 20000) {
                        this.configDeduction = res.data.tixian_rate / 100
                        this.configMinimum = res.data.tixian_min_money
                    } else {
                        this.$dialog.toast({ mes: res.msg, timeout: 1000 });
                    }
                })
                .catch(err => { });
        },
        getUserInfo() {
            let params = {};
            this.$post("/member/get_info", params)
                .then(res => {
                    if (res.code === 20000) {

                        this.phone = res.data.mobile

                        this.name = res.data.alipay_name
                        this.ali = res.data.alipay_num

                        this.imgurl = res.data.weixin_img

                        this.bankName = res.data.bank_card_name
                        this.bankAccount = res.data.bank_card_num
                        this.bankBank = res.data.bank_name

                    } else {
                        this.$dialog.toast({ mes: res.msg, timeout: 1000 });
                    }
                })
                .catch(err => { });
        },
        getQiniuToken: function () {
            let params = {
                ossType: 'qiniu'
            };
            this.$post("/index/get_upload_token", params)
                .then((res) => {
                    if (res.code === 20000) {
                        this.QINIUtoken = res.data.upload_token
                    }
                }).catch((res) => {
                })
        },
    },
    beforeCreate() {
        document.querySelector("body").setAttribute("style", "background-color:#e1deff");
    },
    created() {
        // 实例创建完成
        this.getQiniuToken()
        this.getConfig()
        this.getUserInfo()
    },
};
</script>
<style lang="less" scoped>
@import url("../../asset/css/drawMoney");
</style>